package com.tuangou.tuangougoods.goods.service.impl;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.tuangou.tuangougoods.goods.dao.TypeDao;
import com.tuangou.tuangougoods.goods.entity.TypeEntity;
import com.tuangou.tuangougoods.goods.service.TypeService;


@Service("typeService")
public class TypeServiceImpl extends ServiceImpl<TypeDao, TypeEntity> implements TypeService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TypeEntity> page = this.page(
                new Query<TypeEntity>().getPage(params),
                new QueryWrapper<TypeEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public HashMap<Object, Object> findTypeList() {
        HashMap<Object, Object> data = new HashMap<>();
        try {
            //查询所有
            List<TypeEntity> alltype = baseMapper.selectList(null);
            //创建集合
            ArrayList<TypeEntity> roottype = new ArrayList<>();
            //遍历数据
            for (TypeEntity entity : alltype){
                //判断父级id是否为空，不为空存入集合
                if (entity.getParentId().intValue()==0){
                    roottype.add(entity);
                }
            }
            /* 根据type类的order排序 */
            //Collections.sort(rootmenu, order());
            //为根菜单设置子菜单，getClild是递归调用的
            for (TypeEntity entity : roottype){
                List<TypeEntity> childList = getChild(entity.getTypeId(), alltype);
                entity.setChildren(childList);
            }

            data.put("code","0");
            data.put("msg","ok");
            data.put("result",roottype);

            return data;

        }catch (Exception e){
            data.put("code","-1");
            data.put("result",new ArrayList());
            return data;
        }
    }

    public List<TypeEntity> getChild(Integer id, List<TypeEntity> alltype) {

        ArrayList<TypeEntity> childList = new ArrayList<>();

        for (TypeEntity entity : alltype){
            //遍历所有节点，将所有菜单的父id与传过来的根节点id比较
            //相等说明：为该根节点的子节点
            if(entity.getParentId().intValue()==id.intValue()){
                childList.add(entity);
            }
        }
        //递归
        for (TypeEntity entity : childList){
            entity.setChildren(getChild(entity.getTypeId(),alltype));
        }
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0){
            return new ArrayList<>();
        }
        return childList;
    }

}